package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 添加购物车
     * @param shoppingCartDTO
     */
    @CacheEvict(
            cacheNames = "shoppingCartCache",
            key = "T(com.sky.context.BaseContext).getCurrentId()",
            condition = "T(com.sky.context.BaseContext).getCurrentId() != null"
    )
    public void addShopping(ShoppingCartDTO shoppingCartDTO) {
        //判断当前要加入的商品是否已经在购物车中
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        shoppingCart.setUserId(BaseContext.getCurrentId());

        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);

        //如果已经存在，则增加商品数量
        if (list != null && list.size() > 0){
            ShoppingCart cart = list.get(0);
            cart.setNumber(cart.getNumber() + 1);
            shoppingCartMapper.update(cart);
        } else {
            //如果不存在，则要添加到购物车，数量默认为1
            Long dishId = shoppingCartDTO.getDishId();
            if (dishId != null){
                //本次添加的是菜品
                Dish dish = dishMapper.getById(dishId);
                shoppingCart.setName(dish.getName());
                shoppingCart.setImage(dish.getImage());
                shoppingCart.setAmount(dish.getPrice());
            }else {
                //本次添加的是套餐
                Long setmealId = shoppingCartDTO.getSetmealId();
                Setmeal setmeal = setmealMapper.getByID(setmealId);
                shoppingCart.setName(setmeal.getName());
                shoppingCart.setImage(setmeal.getImage());
                shoppingCart.setAmount(setmeal.getPrice());
            }
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        }

    }

    /**
     * 查看购物车
     * @return
     */
    @Cacheable(
            cacheNames = "shoppingCartCache",
            key = "T(com.sky.context.BaseContext).getCurrentId()"
    )
    public List<ShoppingCart> showShoppingCart() {
        Long currentId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(currentId)
                .build();
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        return list;
    }

    /**
     * 清空购物车
     */
    @CacheEvict(
            cacheNames = "shoppingCartCache",
            key = "T(com.sky.context.BaseContext).getCurrentId()"
    )
    public void cleanShoppingCart() {
        Long userId = BaseContext.getCurrentId();
        shoppingCartMapper.deleteByUserId(userId);
    }

    /**
     * 删除购物车中的商品
     * @param shoppingCartDTO 购物车数据传输对象
     */
    @CacheEvict(
            cacheNames = "shoppingCartCache",
            key = "T(com.sky.context.BaseContext).getCurrentId()",
            // 新增：仅登录用户（userId非null）才清理缓存
            condition = "T(com.sky.context.BaseContext).getCurrentId() != null"
    )
    public void sub(ShoppingCartDTO shoppingCartDTO) {
        // 1. 校验用户是否登录
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new RuntimeException("用户未登录，无法操作购物车");
        }

        // 2. 构造查询条件并设置用户ID
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);
        shoppingCart.setUserId(userId); // 此时userId一定非null

        // 3. 查询购物车中是否存在该商品
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);

        // 4. 如果商品存在，根据数量进行相应操作
        if (list != null && list.size() > 0) {
            ShoppingCart cart = list.get(0);
            // 如果商品数量大于1，将数量减1
            if (cart.getNumber() > 1) {
                cart.setNumber(cart.getNumber() - 1);
                shoppingCartMapper.update(cart);
            } else {
                // 如果商品数量为1，直接从购物车中删除该商品
                shoppingCartMapper.deleteById(cart.getId());
            }
        }
    }

}
